//手机功能控制器
var productDAL = require('../DAL/productDAL');
var async = require('async');
var categoryDAL = require('../DAL/categoryDAL');
var memberDAL = require('../DAL/memberDAL');
var orderDAL = require('../DAL/orderDAL');
var collectDAL = require('../DAL/collectDAL');
var cartDAL = require('../DAL/cartDAL');
var CartInfo = require('../Model/CartInfo');


function mobileController(app) {
	// body...
	/* GET home page. */
	//app.get方法第一个参数是我们添加网站可以请求的地址

	//移动设备首页
	app.get('/mobile/', function(req, res) {
		res.render('mobile/index');
	});

	app.get('/mobile/index', function(req, res) {
		res.redirect('/mobile/');
	});

	//移动搜索页面
	app.get('/mobile/search', function(req, res, next) {
		//res.render方法的第一个参数是我们请求地址对应的网页文件名
		res.render('mobile/search', {
			title: 'Express'
		});

	});

	//搜索页面结果
	app.get('/mobile/searchresult', function(req, res) {
		var q = req.query.q;
		//var currentpage = req.query.js;

		if(q == null) {
			res.redirect('/mobile/searchresult?q=');
		}

		//手机搜索不需要分页
		var currentpage = 1
			//手机搜索页面目前只让其显示搜索结果的前50条
			//设置分页 每页显示数据条数
		var pageSize = 50;

		if(q == null || q == '') {
			res.render('mobile/searchresult', {
				productlist: '',
				q: q
			});
		} else {
			productDAL.searchGoodsByKey(q, currentpage, pageSize, function(productlist) {
				res.render('mobile/searchresult', {
					productlist: productlist,
					q: q
				});
			});
		}
	});

	//手机个人首页
	app.get('/mobile/me', function(req, res) {

		var userInfo = req.session.customer;
		//验证登录
		if(!userInfo) {
			res.redirect('/mobile/login');
		} else {
			//应用async模块的api:parallel处理并行无关联操作
			async.parallel({ //控制流程1:订单数量
				orderCount: function(done) {
					//处理逻辑
					orderDAL.getOrdersCountsByCostomerID(userInfo.customer_Id,function(count) {						
						done(null, count);
					});
				},//控制流程2：收藏数量
				collectCount:function(done){
					collectDAL.getCollectCounts(userInfo.customer_Id,function(count){
						done(null,count);
					});
				}
			}, function(err, results) {
				res.render('mobile/me', {
					userInfo: userInfo,
					orderCount:results.orderCount,
					collectCount:results.collectCount
				});
			});
		}

	});

	//手机分类页面
	app.get('/mobile/catelist', function(req, res) {

		//应用async模块的api:parallel处理并行无关联操作
		async.parallel({ //控制流程1:多级菜单加载
			categorylist: function(done) {
				//处理逻辑
				categoryDAL.getCategoryAll(function(catelist) {
					//循环构造数组对象模型
					var categorylist = create_objectArrayList(catelist, 0);

					done(null, categorylist);
				});

			}
		}, function(err, results) {

			res.render('mobile/category', {
				categorylist: results.categorylist
			});

		});

	});

	//手机分类产品列表页面
	app.get('/mobile/pdlist/:id',function(req,res){
		var category_id = req.params.id;

		productDAL.getTopNumGoodlistByCategoryId(category_id,50,function(pdlist){
			res.render('mobile/pdlist',{
				productlist:pdlist
			});
		});
	});

	//递归构造树型数组对象
	function create_objectArrayList(data, pid) {
		pid = pid || 0;
		var list = [];
		data.map(function(item) {
			if(item.up_id == pid) {
				item.list = create_objectArrayList(data, item.category_Id);
				list.push(item);
			}
		});
		return list;
	}

	//手机登录页面
	app.get('/mobile/login', function(req, res) {
		res.render('mobile/login');
	});
    
    //手机验证登录处理方法
	app.post('/mobile/loginhandle', function(req, res) {
		var user_name = req.body.user_name;
		var user_pass = req.body.user_pass;

		//console.log(user_name+' '+ user_pass);
		if(user_name == "" || user_pass == "") {
			return false;
			res.redirect('/mobile/login');
		}

		//验证登录
		memberDAL.validateLogin(user_name, user_pass, function(message, userInfo, status) {
			//      	
			if(status) {
				//登录成功
				var target_url=req.session.redirecturl;
				if(!target_url){
					target_url='/mobile/me';
				}
				req.session.customer = userInfo;
				res.status(200).send({
					url: target_url,
					message: '登录成功'
				});
			} else {
				//登录失败
				//res.redirect('/login');
				res.status(200).send({
					url: '/mobile/login',
					message: '未登录'
				});
			}
		});
	});

	//手机购物车页面
	app.get('/mobile/cart',function(req,res){

        //用户必须先登录才能从数据库读取购物车记录并进行加载
		//验证登录
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.redirect('/mobile/login');
		}

		//应用async模块的api:parallel处理并行无关联操作
		async.parallel({ 
			 //控制流程2：加载购物车数据
			cartlist: function(done) {
				//购物车数据
				cartDAL.getAllCartData(userInfo.customer_Id, function(datalist) {
					// body...
					//console.log(datalist);
					done(null, datalist);
				});
			}
		}, function(err, results) {

			res.render('mobile/cart', {				
				cartlist: results.cartlist,
				userInfo: userInfo
			});
		});
	});

	//删除多条购物车商品的异步处理方法
	app.post('/mobile/deleteMultiCartHandle',function(req,res){
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.status(200).send({
				url: '/mobile/login',
				message: '未登录'
			});
		} else {
			var pdIdList=req.body.pdIdList;

			console.log('pdIdList:'+pdIdList);

			cartDAL.removeMultiGoodsFormCart(userInfo.customer_Id,pdIdList,function(results){
				if(results){
					res.status(200).send({
					    url: '/mobile/cart',
					    message: '删除成功'
				    });
				}else{
					console.log('err');
				}
			});
		}
	});
	
	//移入收藏夹按钮异步处理
	app.post('/mobile/moveGoodsFromCartToCollectHandle',function(req,res){
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.status(200).send({
				url: '/mobile/login',
				message: '未登录'
			});
		} else {
			var pdIdList=req.body.pdIdList;

			console.log('pdIdList:'+pdIdList);

			cartDAL.moveMultiGoodsFormCartToCollect(userInfo.customer_Id,pdIdList,function(results){
				if(results){
					res.status(200).send({
					    url: '/mobile/cart',
					    message: '移动成功'
				    });
				}else{
					console.log('err');
					res.status(200).send({
					    url: '/mobile/cart',
					    message: '移动失败'
				    });
				}
			});
		}
	});

	//手机版加入购物车处理函数
	app.post('/mobile/cart/addhandle',function(req,res){
		//目标跳转页面
		var target_url = '/mobile/cart';
		req.session.redirecturl = target_url;

		//用户必须先登录才能从数据库读取购物车记录并进行加载
		//验证登录
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.status(200).send({
				url: '/mobile/login',
				message: '未登录'
			});
		} else {
			//获取表单提交数据
			var product_Id = req.body.product_Id;
			var customer_Id = userInfo.customer_Id;
			var num = req.body.goods_num;

			//设置数据对象
			var cartInfo = new CartInfo();
			cartInfo.setproduct_Id(product_Id);
			cartInfo.setcustomer_Id(customer_Id);
			cartInfo.setnum(num);

			//添加购物车数据操作
			cartDAL.addCart(cartInfo, function(message, results) {
				if(results) {
					//加入或者更新成功
					res.status(200).send({
						url: '/mobile/cart',
						message: message
					});
				}
			});
		}
	});

	//手机活动页面
	app.get('/mobile/event',function(req,res){
		res.render('mobile/event');
	});

}

module.exports = mobileController;